//分享官详情
import React from 'react'
import { Space, Modal, message, Typography, Tooltip, Form, Button, Input } from "antd";
import { QuestionCircleOutlined } from '@ant-design/icons';
import TheTable from '@/components/TheTable'
import ThePagination from '@/components/ThePagination'
import TheButton from '@/components/TheButton'
import GoBack from '@/components/TheGoBack'
import TheQueryForm from '@/components/TheQueryForm'
import RejectModal from './rejectModal'
import OrderNumModal from './orderNumModal'
import PetLoverModal from './petLoverModal'
import ActivePopulationModal from './activePopulationModal'
import { getDateTime3 } from '@/utils/getDate'
import { sharerDetailsInfo, sharerExamine, sharedState, sharedListExport } from '@/request/distribution/sharerManagement.js'
const { Title } = Typography;
const { TextArea } = Input
export default class SharerManagementDetails extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      sharedById: null, //分享官id
      queryForm: {},
      basicInfoColumns: [
        {
          title: "会员ID",
          dataIndex: "memberId",
          key: "memberId",
        },
        {
          title: "用户昵称",
          dataIndex: "username",
          key: "username",
        },
        {
          title: "实名姓名",
          dataIndex: "realName",
          key: "realName",
          render: (text) => {
            let str = ''
            if(text) {
              if (text.length === 2) {
                str = text.substr(0, 1) + '*';
              } else if (text.length > 2) {
                let char = '';
                for (let i = 0, len = text.length - 2; i < len; i++) {
                  char += '*';
                }
                str = text.substr(0, 1) + char + text.substr(-1, 1);
              } else {
                str = text;
              }
            }else {
              str = "未实名"
            }
            return str
          }
        },
        {
          title: "地址",
          render: (_, record) => {
            return <Tooltip title={record.province + record.city + record.district + record.address}>
              <span style={{ display: 'flex', flexWrap: 'wrap', whiteSpace: 'pre-wrap', wordBreak: 'break-all', justifyContent: 'center' }}>{record.province + record.city + record.district + record.address}</span>
            </Tooltip>
          }
        },
        {
          title: "会员手机号",
          dataIndex: "memberMobile",
          key: "memberMobile",
        },
        {
          title: "时间",
          render: (_, record) => {
            return <>{record.sharedLevel === "0" ? "-" 
              :<Space direction='vertical'>
                <span>申请时间：{record.createTime}</span>
                {/* <span>{record.status === 2 ? "驳回时间：" + record.blackTime : ""}</span> */}
                <span>加入时间：{record.bindTime}</span>
                <span>{record.status === 3 ? "拉黑时间：" + record.blackTime : ""}</span>
              </Space>
            }</>
          }
        },
        {
          title: "状态",
          dataIndex: "status",
          key: "status",
          render: (text, record) => {
            let status = ''
            switch (text) {
              case 0:
                status = '待审核'
                break
              case 1:
                status = '正常'
                break
              case 2:
                status = `驳回\n(${record.rejectMessage})`
                break
              case 3:
                status = <p>拉黑<br />({record.blackMessage})</p>
                break
              default:
                status = '-'
            }
            return <Tooltip title={status}>
              <span style={{ display: 'flex', flexWrap: 'wrap', whiteSpace: 'pre-wrap', wordBreak: 'break-all', justifyContent: 'center' }}>{status}</span>
            </Tooltip>
          }
        }
      ],//基础信息表头
      basicInfoDataSource: [],//基础信息
      searchOption: [{ field: 'time', label: '时间', type: 'RangePicker', }],
      basicDataColumns: [
        {
          title: "商品分享次数",
          width: 150,
          dataIndex: "goodsShareTotalCount",
          key: "goodsShareTotalCount",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => { return <span>统计时间段，分享官将商品分享给其他用户的次数。</span> }}  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
          render: (_, record) => {
            return (
              <Space direction='vertical'>
                {<span>合计:{record.shareInfoDTO.goodsShareTotalCount}</span>}
                {<span>微信好友:{record.shareInfoDTO.goodsShareFriendCount}</span>}
                {<span>朋友圈:{record.shareInfoDTO.goodsShareCircleCount}</span>}
                {<span>下载图片:{record.shareInfoDTO.goodsShareImgCount}</span>}
              </Space>
            )
          }
        },
        {
          title: "商品分享注册人数",
          width: 200,
          dataIndex: "goodsShareInviteMemberCount",
          key: "goodsShareInviteMemberCount",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => { return <span>统计时间段，分享官将商品分享给其他用户 ，产生的新用户注册数。</span> }}  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
          render: (_, record) => {
            return record.shareInfoDTO.goodsShareInviteMemberCount ?? "-"
          }
        },
        {
          title: "商品分享下单人数",
          width: 200,
          dataIndex: "goodsShareCreateOrderCount",
          key: "goodsShareCreateOrderCount",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => { return <span>爱宠成员用户通过分享官分享的商品完成整个购买流程 （统计时间范围内一个用户多次下单，只计算一人。）</span> }}  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
          render: (_, record) => {
            return record.shareInfoDTO.goodsShareCreateOrderCount ?? "-"
          }
        },
        {
          title: "活动分享次数",
          width: 150,
          dataIndex: "activityShareTotalCount",
          key: "activityShareTotalCount",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => { return <span>统计时间段，分享官将拉新活动分享给其他用户的次数。</span> }}  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
          render: (_, record) => {
            return (
              <Space direction='vertical'>
                {<span>合计:{record.shareInfoDTO.activityShareTotalCount}</span>}
                {<span>微信好友:{record.shareInfoDTO.activityShareFriendCount}</span>}
                {<span>朋友圈:{record.shareInfoDTO.activityShareCircleCount}</span>}
              </Space>
            )
          }
        },
        {
          title: "活动分享注册人数",
          width: 200,
          dataIndex: "activityShareInviteMemberCount",
          key: "activityShareInviteMemberCount",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => { return <span>通过分享官分享的活动 产生的新用户注册数。</span> }}  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
          render: (_, record) => {
            return record.shareInfoDTO.activityShareInviteMemberCount ?? "-"
          }
        },
        {
          title: "爱宠成员数",
          width: 150,
          dataIndex: "petLovingMemberCount",
          key: "petLovingMemberCount",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => { return <span>统计时间段,加入的爱宠成员统计数量</span> }}  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
          render: (text, record) => {
            return <Space direction='vertical'>
              {text ?? "-"}
              {<TheButton haspermi={['distribution:sharerManagement:petLoverModal']} onClick={() => { this.petLoverModalRef.openModal(record.sharedById, this.state.queryForm) }}>查看</TheButton>}
            </Space>
          }
        },
        {
          title: "累积下单人数",
          width: 150,
          dataIndex: "shareOrderTotalMemberCount",
          key: "shareOrderTotalMemberCount",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => { return <span>每天订单支付成功的会员数去重，并按照统计天数增加所得</span> }}  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
          render: (text, record) => {
            return <Space direction='vertical'>
              {record.shareOrderDTO.shareOrderTotalMemberCount ?? "-"}
              {<TheButton haspermi={['distribution:sharerManagement:orderNumModal']} onClick={() => { this.orderNumModalRef.openModal(record.sharedById, this.state.queryForm) }}>查看</TheButton>}
            </Space>
          }
        },
        {
          title: "当天下单人数",
          width: 150,
          dataIndex: "shareOrderTodayMemberCount",
          key: "shareOrderTodayMemberCount",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => { return <span>当天，成功支付订单的人数 （统计时间范围内一个用户多次下单，只计算一人）</span> }}  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
          render: (_, record) => {
            return record.shareOrderDTO.shareOrderTodayMemberCount ?? "-"
          }
        },
        {
          title: "当天退单人数",
          width: 150,
          dataIndex: "shareOrderTodayToRefundMemberCount",
          key: "shareOrderTodayToRefundMemberCount",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => { return <span>当天，成功支付订单的人数中，发起退单人数 （不统计退单结果）</span> }}  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
          render: (_, record) => {
            return record.shareOrderDTO.shareOrderTodayToRefundMemberCount ?? "-"
          }
        },
        {
          title: "订单数",
          dataIndex: "shareOrderCount",
          key: "shareOrderCount",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => { return <span>统计时间内，成功支付订单的数量</span> }}  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
          render: (_, record) => {
            return record.shareOrderDTO.shareOrderCount ?? "-"
          }
        },
        {
          title: "退单数",
          dataIndex: "shareOrderRefundCount",
          key: "shareOrderRefundCount",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => { return <span>统计时间内，成功支付订单对应的退单数量</span> }}  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
          render: (_, record) => {
            return record.shareOrderDTO.shareOrderRefundCount ?? "-"
          }
        },
        {
          title: "活跃人数",
          dataIndex: "activeMember",
          key: "activeMember",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => { return <span>统在统计时间内与在哈奇马平台（APP/小程序）进行过至少一次互动的独立用户数量。</span> }}  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
          render: (text, record) => {
            return <Space direction='vertical'>
              {record.shareOrderDTO.activeMember ?? "-"}
              {<TheButton haspermi={['distribution:sharerManagement:activeMemberModal']} onClick={() => { this.activePopulationModalRef.openModal(record.sharedById, this.state.queryForm) }}>查看</TheButton>}
            </Space>
          }
        },
      ],//基础数据表头
      basicDataDataSource: [],//基础数据-
      columns: [
        {
          title: "月份",
          render: (_, record) => {
            return record.toYear + '年' + record.toMonth + '月'
          }
        },
        {
          title: "实付GMV(元)",
          dataIndex: "gmv",
          key: "gmv",
        },
        {
          title: "下单人数（去重）",
          dataIndex: "orderNumber",
          key: "orderNumber",
        },
        {
          title: "当月佣金",
          dataIndex: "commissionRate",
          key: "commissionRate",
          render: (text) => {
            return text ? text + '%' : '-'
          }
        },
      ],//推广效果表头
      dataSource: [], //推广效果数据
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,
      memberId: ""
    }
  }
  componentDidMount() {
    let { id, memberId } = this.props.match.params
    if (id) {
      this.setState({ sharedById: id, memberId }, () => {
        this.getData()
      })
    }
  }
  //数据渲染
  getData = async (values) => {
    let { pageData, sharedById, memberId } = this.state
    if (values && values.hasOwnProperty('time')) {
      values.startTime = getDateTime3(values.time[0]) + " 00:00:00"
      values.endTime = getDateTime3(values.time[1]) + " 23:59:59"
      delete values.time
      this.setState({
        queryForm: values
      })
    }
    await sharerDetailsInfo({ sharedById, ...pageData, ...values }).then(res => {
      if (res.code === 0) {
        this.setState({
          sharedById,
          detailsData: res.data,
          basicInfoDataSource: [res.data],
          dataSource: res.data.shareRewardsVOIPage.records,
          pageData: {
            pageNo: 1,
            pageSize: 10
          },
          total: 0
        })
      }
    })
    await sharedListExport({ sharedById, ...values, fillerSharedBy: "1" }).then(res => {
      if (res.code === 0) {
        this.setState({
          basicDataDataSource: res.data
        })
      }
    })
  }
  onFormSearch(values) {
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 },
      queryForm: values
    }, () => {
      this.getData(values)
    })
  }
  //搜索重置
  onReset() {
    this.setState({ queryForm: {} }, () => {
      this.pageChange(1, 10)
    })
  }
  //分页
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo, pageSize
      }
    }, () => {
      this.getData()
    })
  }
  // 通过申请
  passSharer = (sharedById) => {
    Modal.confirm({
      title: '通过审核',
      content: '通过后，该用户将成为高级分享官',
      onOk: async () => {
        await sharerExamine({ sharedById, status: 1 }).then(res => {
          if (res.code === 0) {
            message.success('审核通过!')
            this.props.history.goBack(-1)
          }
        })
      }
    });
  }
  //打开拉黑弹窗
  blacklistModal = (sharedById) => {
    this.setState({ isBlacklistModal: true, sharedById })
  }
  //确认拉黑
  blacklistSubmit = (value) => {
    let { sharedById } = this.state
    this.setState({ blacklistBtnLoading: true }, async () => {
      await sharedState({ sharedById, status: 3, ...value }).then(res => {
        if (res.code === 0) {
          message.success('拉黑成功')
          this.getData()
          this.blacklistClose()
        }
      })
      this.setState({ blacklistBtnLoading: false })
    })
  }
  // 关闭拉黑弹窗
  blacklistClose = () => {
    this.formRef.resetFields()
    this.setState({ isBlacklistModal: false })
  }
  //取消拉黑
  cancelBlacklist = (sharedById) => {
    Modal.confirm({
      title: '取消拉黑',
      content: '取消拉黑，用户产生的订单结算佣金',
      onOk: async () => {
        await sharedState({ sharedById, status: 1 }).then(res => {
          if (res.code === 0) {
            message.success('取消拉黑成功')
            this.getData()
          }
        })
      }
    });
  }

  render() {
    const {
      infoData,
      basicInfoColumns,
      basicInfoDataSource,
      basicDataColumns,
      basicDataDataSource,
      searchOption,
      columns,
      dataSource,
      pageData: { pageNo, pageSize },
      total,
      shareId,
      detailsData,
      blacklistBtnLoading,
      isBlacklistModal
    } = this.state
    return (
      <div className='p-layout-box'>
        <GoBack history={this.props.history} title='分享官详情'></GoBack>
        <Title style={{ marginTop: 10 }} level={5}>基础信息</Title>
        <TheTable scroll={{ x: "max-content" }} columns={basicInfoColumns} dataSource={basicInfoDataSource} rowKey={record => record.memberId} />
        <Title style={{ marginTop: 10 }} level={5}>基础数据</Title>
        <TheQueryForm
          ref={(ref) => this.queryFormRef = ref}
          option={searchOption}
          show={true}
          onReset={() => this.onReset()}
          onGetValues={(values) => this.onFormSearch(values)} />
        <TheTable columns={basicDataColumns} dataSource={basicDataDataSource} rowKey={record => record.memberId} />
        <Title style={{ marginTop: 10 }} level={5}>推广效果</Title>
        <TheTable columns={columns} dataSource={dataSource} rowKey={record => record.memberId} />
        <ThePagination
          pageNo={pageNo}
          pageSize={pageSize}
          total={total}
          pageChange={this.pageChange}
        />
        {
          detailsData && detailsData.memberLevel === '高级分享官' && <div style={{ margin: 'auto' }}>
            {/* 待审核状态显示按钮 */}
            {
              detailsData && detailsData.status === 0 &&
              <Space style={{ margin: 'auto' }}>
                <TheButton size="middle" type='default' onClick={() => { this.rejectModalRef.openRejectModal(this.props.match.params.id) }}>驳回</TheButton>
                <TheButton size="middle" type='primary' onClick={() => { this.passSharer(this.props.match.params.id) }}>通过</TheButton>
              </Space>
            }
            { // 状态正常状态时显示拉黑
              detailsData && detailsData.status === 1 &&
              <Space style={{ margin: 'auto' }}>
                <TheButton size="middle" type='default' onClick={() => { this.blacklistModal(detailsData.sharedById) }}>拉黑</TheButton>
              </Space>
            }
            { // 状态拉黑状态时显示取消拉黑
              detailsData && detailsData.status === 3 &&
              <Space style={{ margin: 'auto' }}>
                <TheButton size="middle" type='default' onClick={() => { this.cancelBlacklist(detailsData.sharedById) }}>取消拉黑</TheButton>
              </Space>
            }
          </div>
        }

        {/* 驳回申请弹窗 */}
        <RejectModal ref={(ref) => this.rejectModalRef = ref} history={this.props.history} type='view'></RejectModal>
        {/* 拉黑弹窗 */}
        <Modal title="拉黑" visible={isBlacklistModal} footer={null} destroyOnClose onCancel={() => { this.blacklistClose() }}>
          <div style={{ marginBottom: 20 }}>拉黑期间，爱宠分享官产生的订单不予结算佣金</div>
          <Form onFinish={this.blacklistSubmit} ref={(ref) => this.formRef = ref}>
            <Form.Item label="拉黑原因" name="blackMessage" rules={[{ required: true }]}  >
              <TextArea placeholder='拉黑原因将向用户展示，请输入拉黑原因（1-100字）' maxLength={100} autoSize={{ minRows: 6, maxRows: 6 }} showCount />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 8, span: 16 }} >
              <Space>
                <Button onClick={() => { this.blacklistClose() }}>取消</Button>
                <Button type="primary" htmlType="submit" loading={blacklistBtnLoading}>确定</Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal >
        {/* 下单人数弹窗 */}
        <OrderNumModal ref={(ref) => this.orderNumModalRef = ref}></OrderNumModal>
        {/* 爱宠成员弹窗 */}
        <PetLoverModal ref={(ref) => this.petLoverModalRef = ref}></PetLoverModal>
        {/* 活跃人数弹窗 */}
        <ActivePopulationModal ref={(ref) => this.activePopulationModalRef = ref}></ActivePopulationModal>
      </div>
    )
  }
}
